--/run for k,v in pairs(C_PetBattles.GetAllStates()) do local a = C_PetBattles.GetStateValue(2,1,v)  print(v,k,a) end
--/run  print(C_PetBattles.GetAbilityEffectInfo(C_PetBattles.GetAbilityInfo(1,1, 3),2,1,"accuracy"),"|n",C_PetBattles.GetAbilityInfo(1,1, 3))


local STATE_Stat_Accuracy = 41
local STATE_Stat_Dodge = 73
local BASE_MISS_CHANCE = 5
local effectLongString = "Effect %d: %d%% Chance to hit"
local effectShortString = "%d%% Chance to hit"
local turnFormatString = "Turn %d: %s"
local outputFormatString = "%s|n|n|cFF03FBFF%s|r"
PetBattleInfo = {}


local function GetAccuracy(abilityID,turn)
	if not abilityID then return end
	
	local effects = {}
	local stringBuilder = {}
	local count = 0
	for effect =1,10 do
		local value = C_PetBattles.GetAbilityEffectInfo(abilityID,turn,effect,"accuracy")
		if value then
			effects[effect] = value
			count = count + 1
		end
	end
	
	for k,v in pairs(effects) do
		if count > 1 then
			table.insert(stringBuilder,string.format(effectLongString,k,v))
		else
			table.insert(stringBuilder,string.format(effectShortString,v))
		end
	end
	
	local finalString = table.concat(stringBuilder,"|n")
	return finalString,count
end

local function  PetBattleUnitTooltip_UpdateForUnit_Hook(self, petOwner, petIndex)
	if petOwner and petIndex then
		self.petOwner = petOwner
		self.petIndex = petIndex
		--Show and update abilities
		self.AbilitiesLabel:Show();
		local enemyPetType = C_PetBattles.GetPetType(PetBattleUtil_GetOtherPlayer(petOwner), C_PetBattles.GetActivePet(PetBattleUtil_GetOtherPlayer(petOwner)));
		for i=1, NUM_BATTLE_PET_ABILITIES do
			local id, name, icon, maxCooldown, description, numTurns, abilityPetType, noStrongWeakHints = C_PetBattles.GetAbilityInfo(petOwner, petIndex, i);
			
			local isUsable, currentCooldown = C_PetBattles.GetAbilityState(petOwner, petIndex, i);
			
			local abilityIcon = self["AbilityIcon"..i];
			local abilityName = self["AbilityName"..i];
			if ( id ) then
				local modifier = 1.0;
				if (abilityPetType and enemyPetType) then
					modifier = C_PetBattles.GetAttackModifier(abilityPetType, enemyPetType);
				end
				
				if ( noStrongWeakHints or modifier == 1 ) then
					abilityIcon:SetTexture("Interface\\PetBattles\\BattleBar-AbilityBadge-Neutral");
				elseif ( modifier < 1 ) then
					abilityIcon:SetTexture("Interface\\PetBattles\\BattleBar-AbilityBadge-Weak");
				elseif ( modifier > 1 ) then
					abilityIcon:SetTexture("Interface\\PetBattles\\BattleBar-AbilityBadge-Strong");
				end
				
				
				local cdMessage = ""
				if PetBattleInfo.db.global.display.cooldown then
					if maxCooldown > 0 and currentCooldown and currentCooldown > 0 then
						if numTurns > 1 and  currentCooldown == maxCooldown then 
							cdMessage  = "|cFFFF0000In "..currentCooldown.."+ Turns|r"
						else
							cdMessage  = "|cFFFF0000In "..currentCooldown.." Turns|r"
						end
					elseif maxCooldown > 0 and currentCooldown ~= nil and currentCooldown == 0 then
						cdMessage  = "|cFF00FF00Is Available|r"
					else
						cdMessage  = "|cFF00FF00No Cooldown|r"
					end
					abilityName:SetText(string.format("%s|n%s",name,cdMessage))
					abilityName:SetSize(120,28)
				else
					abilityName:SetText(name)
				end
				
				
				abilityIcon:Show();
				abilityName:Show();
			else
				abilityIcon:Hide();
				abilityName:Hide();
			end
		end
	end
end

local function SharedPetBattleAbilityTooltip_SetAbility_Hook(self,PET_BATTLE_ABILITY_INFO)
	if not PetBattleInfo.db.global.display.accuracy then return end
	
	local description = self.Description:GetText()
	local id =  PET_BATTLE_ABILITY_INFO.abilityID  or C_PetBattles.GetAbilityInfo(PET_BATTLE_ABILITY_INFO.petOwner,PET_BATTLE_ABILITY_INFO.petIndex,PET_BATTLE_ABILITY_INFO.abilityIndex)
	local stringbuilder = {}
	
	if not id then return end
	
	for i=1,10 do
		local accuracyText,count = GetAccuracy(id,i)
		if count == 0 then
			if i == 2 then
				wipe(stringbuilder)
				accuracyText = GetAccuracy(id,1)
				table.insert(stringbuilder,accuracyText )
			end
			break
		end
		
		if count > 1 then
			table.insert(stringbuilder,string.format(turnFormatString,i,""))
			table.insert(stringbuilder,accuracyText)
		elseif count == 1 then
			table.insert(stringbuilder,string.format(turnFormatString,i,accuracyText))
		end
	end
	local finalString =table.concat(stringbuilder,"|n")
	self.Description:SetText(string.format(outputFormatString,description,finalString))
end

local function OnInitialize()
	
	
	local defaults = {
		global = {
			display = {
				accuracy = true,
				breed = false,
				glow = true,
				cooldown = true,
			},
		}
	}
	PetBattleInfo.db = LibStub("AceDB-3.0"):New("PetBattleInfoDB", defaults, true)
	
	local display = PetBattleInfo.db.global.display
	local config = {
		name = "PetBattle Info",
		handler = self,
		type = 'group',
		args = {
			showAccuracy = {
				order = 1,
				name = "Display the accuracy of abilities",
				type = "toggle",
				width = "double",
				set = function(info,val) 
						display.accuracy = val
				end,
				get = function(info) return display.accuracy or false end
			},
			showGlow = {
				order = 10,
				name = "Display additional quality information during pet battles",
				type = "toggle",
				width = "double",
				set = function(info,val) 
						display.glow = val
				end,
				get = function(info) return display.glow or false end
			},
			showBreed = {
				order = 20,
				name = "Display Breed information during pet battles",
				type = "toggle",
				width = "double",
				set = function(info,val) 
						display.breed = val
				end,
				get = function(info) return display.breed or false end
			},
			showCooldowns = {
				order = 30,
				name = "Display the cooldowns of abilities in the pet tooltip",
				type = "toggle",
				width = "double",
				set = function(info,val) 
						display.cooldown = val
				end,
				get = function(info) return display.cooldown or false end
			},
			
		},
	}
	LibStub("AceConfig-3.0"):RegisterOptionsTable("PetBattleInfo", config)
    LibStub("AceConfigDialog-3.0"):AddToBlizOptions("PetBattleInfo","PetBattle Info")
end

local function OnEvent(self,event,arg1,...)
	
	if event == "PET_BATTLE_PET_ROUND_PLAYBACK_COMPLETE" and  PetBattlePrimaryUnitTooltip:IsShown() then
		PetBattleUnitTooltip_UpdateForUnit_Hook(PetBattlePrimaryUnitTooltip,PetBattlePrimaryUnitTooltip.petOwner,PetBattlePrimaryUnitTooltip.petIndex)
	elseif event == "ADDON_LOADED" and arg1 == "PetBattleInfo" then
		OnInitialize()
		self:UnregisterEvent("ADDON_LOADED")
	elseif event=="PLAYER_ENTERING_WORLD" then
		if IsAddOnLoaded("BattlePetBreedID") then
			PetBattleInfo.db.global.display.breed = false
		end
	end
	
	
end

local eventFrame = CreateFrame("frame")
eventFrame:RegisterEvent("PET_BATTLE_PET_ROUND_PLAYBACK_COMPLETE")
eventFrame:SetScript("OnEvent",OnEvent)
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")

hooksecurefunc("PetBattleUnitTooltip_UpdateForUnit",PetBattleUnitTooltip_UpdateForUnit_Hook)
hooksecurefunc("SharedPetBattleAbilityTooltip_SetAbility",SharedPetBattleAbilityTooltip_SetAbility_Hook)